package com.freak.freakmusic.base

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.freak.freakmusic.app.App
import com.freak.freakmusic.event.LoginOutEvent
import com.freak.freakmusic.net.status.NetStateChangeObserver
import com.freak.freakmusic.net.status.NetStateChangeReceiver
import com.freak.freakmusic.net.status.NetworkType
import com.freak.freakmusic.utils.ToastUtil
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

open class BaseActivity : AppCompatActivity(), NetStateChangeObserver {
    private var mActivity: AppCompatActivity? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //活动控制器
        mActivity = this
        App.instance!!.addActivity(this, this.javaClass)
        EventBus.getDefault().register(this)
    }

    override fun onRestart() {
        super.onRestart()

    }

    override fun onStart() {
        super.onStart()
    }

    override fun onResume() {
        super.onResume()
        if (needRegisterNetworkChangeObserver()) {
            NetStateChangeReceiver.registerObserver(this)
        }
    }

    override fun onPause() {
        super.onPause()
    }

    override fun onStop() {
        super.onStop()
    }

    override fun onDestroy() {
        super.onDestroy()
        App.instance?.removeActivity(this)
        if (needRegisterNetworkChangeObserver()) {
            NetStateChangeReceiver.unregisterObserver(this)
        }
        EventBus.getDefault().unregister(this)
    }


    /**
     * 是否需要注册网络变化的Observer,如果不需要监听网络变化,则返回false;否则返回true
     */
    protected fun needRegisterNetworkChangeObserver(): Boolean {
        return true
    }

    /**
     * 网络断开时执行的操作
     */
    override fun onNetDisconnected() {
        showDisConnectedView()
    }

    /**
     * 网络重连时执行的操作
     *
     * @param networkType
     */
    override fun onNetConnected(networkType: NetworkType) {
        ToastUtil.showLong(this, "当前连接的是" + networkType.toString() + "网络")
        onNetConnectedReLoad()
        hideDisConnectedView()
    }

    protected open fun onNetConnectedReLoad() {

    }

    /**
     * 显示无网络状态
     */
    fun showDisConnectedView() {
        ToastUtil.showLong(this, "网络连接错误，请检测您的网络设置")
        //        netErrorView = findViewById(R.id.rl_net_error);
        //        netErrorView.setVisibility(View.VISIBLE);
    }

    /**
     * 隐藏无网络状态
     */
    fun hideDisConnectedView() {
        //        netErrorView = findViewById(R.id.rl_net_error);
        //        netErrorView.setVisibility(View.GONE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    @Synchronized
    fun doLoginOut(loginOutEvent: LoginOutEvent?) {


    }

}
